package wjl.project.dubbotestshop;

import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericToStringSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession;

import javax.annotation.Resource;
import java.util.List;
@EnableRedisHttpSession
@SpringBootApplication
public class DubboTestShopApplication {

    public static final String MIAOSHA_PREFIX = "miaosha_" ;

    @Resource
    GoodsRepository goodsRepository;

    @Resource
    RedisTemplate<String,String> redisTemplate;

    public static void main(String[] args) {
        SpringApplication.run(DubboTestShopApplication.class, args);
    }

//    StringRedisSerializer将字符串的值直接转为字节数组，所以保存到redis中是数字，所以可以进行加1 ;
    @Bean
    public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        // 1.创建 redisTemplate 模版
        RedisTemplate<Object, Object> template = new RedisTemplate<>();
        // 2.关联 redisConnectionFactory
        template.setConnectionFactory(redisConnectionFactory);
        // 6.序列化类，对象映射设置
        // 7.设置 value 的转化格式和 key 的转化格式
        template.setValueSerializer(new StringRedisSerializer());
        template.setKeySerializer(new StringRedisSerializer());
        template.afterPropertiesSet();
        return template;
    }

    @Bean
    public CommandLineRunner loadGoods(){
        return new CommandLineRunner() {
            @Override
            public void run(String... args) throws Exception {
                List<Goods> goodsList = goodsRepository.findAll();
                for (Goods g: goodsList
                     ) {
                    redisTemplate.opsForValue().set(MIAOSHA_PREFIX+g.getGoodsId(),g.getGoodsNum()+"");
                    System.out.println("初始化商品--"+g.getGoodsId()+"--写入redis ，数量为："+g.getGoodsNum());
                }
            }
        };
    }
}
